<?php

declare(strict_types=1);

namespace App\Model;

use Hyperf\DbConnection\Db;
use Hyperf\DbConnection\Model\Model;

/**
 * 用户免费通话券记录
 */
class UserFreeCall extends Model
{
    protected $table = 'user_free_call_log';
    protected $fillable = ['status', 'used_minutes', 'call_id', 'call_type', 'used_at', 'pay_order_id'];

    const STATUS_OK = 0;
    const STATUS_USED = 1;
    const STATUS_EXP = -1;

    //充值
    const FROM_RECHARGE = 1;
    //新用户赠送
    const FROM_NEW = 2;

    /**
     * 检测是否有可用的免费券
     */
    static function checkValid(
        $userId = 0,
        $offDate = '',
        $status = self::STATUS_OK,
        $dataType = 'item',
        $from = 0
    ) {
        $where = [
            ['user_id', $userId],
        ];
        $offDate && $where[] = ['created_at', '>', (string)$offDate];
        $status >= -1 && $where[] = ['status', $status];
        $from > 0 && $where[] = ['from', $from];
        if ('count' == $dataType) return self::where($where)->count();
        else return self::where($where)->orderBy('id', 'desc')->first();
    }

    /**
     * 赠送免费通话券
     */
    static function addRecord($userId = 0, $minutes = 0, $extraInfo = [], $from = self::FROM_RECHARGE)
    {
        $model = new self();
        $model->user_id = $userId;
        $model->free_minutes = $minutes;
        $model->from = $from;
        $model->pay_order_id = $extraInfo['pay_order_id'] ?? 0;
        $model->status = self::STATUS_OK;
        return $model->saveOrFail() ? 1 : 0;
    }

    /**
     * 根据话单ID获取免费券记录
     */
    static function checkByCallId($callId = 0, $callType = VoiceCall::CALL_TYPE)
    {
        $where = [
            'call_id' => $callId,
            'call_type' => $callType
        ];
        return self::where($where)->orderBy('id', 'desc')->first();
    }
}
